package activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import bean.EntityForSimple;
import fragmentson.ChangePassword;
import fragmentson.DeviceList;
import fragmentson.DeviceListDemo;
import fragmentson.FindCarNotice_A;
import fragmentson.FindCarNotice_B;
import fragmentson.Fortify;
import fragmentson.LogonFragment_A;
import fragmentson.MessageList;
import fragmentson.MessageParticulars;
import fragmentson.NoticeHistory;
import fragmentson.Pay;
import fragmentson.Rall_A;
import fragmentson.RemainingSum;
import fragmentson.ReportLoss_A;
import fragmentson.ReportLoss_B;
import fragmentson.ShopParticulars;
import fragmentson.SwitchMenu;
import fragmentson.Trace;
import fragmentson.Track;
import fragmentson.UserInfo;
import fragmentson.backhandle.BackHandledFragment;
import fragmentson.backhandle.BackHandledInterface;
import util.dialog.DialogFromMiddle;
import util.pay.alpay.PayResult;
import util.pay.wxpay.Constants;
import util.pay.wxpay.MD5;

/**
 * 子页面activity
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class SonActivity extends FragmentActivity
		implements BackHandledInterface {
	
	private int code;
	private Fragment f = null;
	private BackHandledFragment mBackHandedFragment;

	//微信支付
	private StringBuffer sb;
	private Map<String,String> resultunifiedorder;
	private PayReq req;
	private final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
	//支付宝
	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_CHECK_FLAG = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DemoApplication.addActivity(this);
		code = getIntent().getIntExtra("code", 0);
		setContentView(R.layout.activity_son);
		initFragment();
	}

	/**
	 * 根据code加载指定fragment
	 */
	private void initFragment() {
		// TODO Auto-generated method stub
		switch (code) {
			case 1:
				f = LogonFragment_A.newInstance();
				break;
			case 2:
				f = ChangePassword.newInstance();
				break;
			case 9:
				f= UserInfo.newInstance();
				break;
			case 12:
				f = Rall_A.newInstance();
				break;
			case 13:
				f = Trace.newInstance();
				break;
			case 15:
				f = Track.newInstance();
				break;
			case 17:
				f = SwitchMenu.newInstance();
				break;
			case 18:
				f = MessageList.newInstance();
				break;
			case 19:
				f = MessageParticulars.newInstance(getIntent().getExtras().getString("lat"),getIntent().getExtras().getString("lng"),getIntent().getExtras().getString("name"),getIntent().getExtras().getString("content"),getIntent().getExtras().getString("time"));
				break;
			case 20:
				f = Pay.newInstance();
				break;
			case 24:
				f = MessageList.newInstance();
				break;
			case 25:
				f = MessageParticulars.newInstance(getIntent().getExtras().getString("lat"),getIntent().getExtras().getString("lng"),getIntent().getExtras().getString("name"),getIntent().getExtras().getString("content"),getIntent().getExtras().getString("time"));
				break;
			case 26:
				f = Fortify.newInstance();
				break;
			case 27:
				f = ReportLoss_A.newInstance();
				break;
			case 28:
				f = FindCarNotice_A.newInstance();
				break;
			case 29:
				f = DeviceList.newInstance();
				break;
			case 30:
				f = ShopParticulars.newInstance((EntityForSimple) getIntent().getSerializableExtra("mData"));
				break;
			case 32:
				f = NoticeHistory.newInstance();
				break;
			case 33:
				f = ReportLoss_B.newInstance();
				break;
			case 34:
				f = RemainingSum.newInstance();
				break;
			case 35:
				f = FindCarNotice_B.newInstance();
				break;
			case 36:
				f = DeviceListDemo.newInstance();
				break;
			default:
				break;
		}
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.replace(R.id.contentfragment, f);
		ft.addToBackStack("tag");
		ft.commit();
	}

	@Override
	public void setSelectedFragment(BackHandledFragment selectedFragment) {
		// TODO Auto-generated method stub
		this.mBackHandedFragment = selectedFragment;
	}

	@Override
	public void onBackPressed() {
		if (mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()) {
			if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
				finish();
			} else {
				getSupportFragmentManager().popBackStack();
			}
		}
	}

	/**
	 * 加入到activity
	 * @param fragment 已选择的fragment
	 */
	public void addFragment(Fragment fragment) {
		Fragment f = fragment;
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		int animIn = R.anim.slide_right_in;
		int animOut = R.anim.slide_left_out;
		int popIn = R.anim.slide_left_in;
		int popOut = R.anim.slide_right_out;
		ft.setCustomAnimations(animIn, animOut, popIn, popOut);
		ft.replace(R.id.contentfragment, f);
		ft.addToBackStack("tag1");
		ft.commit();
	}
	/**
	 * 加入到activity
	 * @param fragment 已选择的fragment
	 */
	public void addFragment(Fragment fragment,boolean isadd) {
		Fragment f = fragment;
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		int animIn = R.anim.slide_right_in;
		int animOut = R.anim.slide_left_out;
		int popIn = R.anim.slide_left_in;
		int popOut = R.anim.slide_right_out;
		ft.setCustomAnimations(animIn, animOut, popIn, popOut);
		ft.add(R.id.contentfragment, f);
		ft.addToBackStack("tag1");
		ft.commit();
	}

	/**
	 * 返回处理逻辑
	 */
	public void backTask() {
		if (mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()) {
			if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
				finish();
			} else {
				getSupportFragmentManager().popBackStack();
			}
		}
	}

	public void back(View v) {
		backTask();
	}


	/*微信支付 从接口拿到prepay_id后一次吊起genPayReq() sendPayReq()*/
	/*
	 * 调起微信支付
	 */
	private void sendPayReq() {
		msgApi.registerApp(Constants.APP_ID);
		msgApi.sendReq(req);
		Log.i(">>>>>", req.partnerId);
	}
	/**
	 * 先生成签名参数 然后吊起微信
	 */
	private void genPayReq() {
		req.appId = Constants.APP_ID;
		req.partnerId = Constants.MCH_ID;
		if (resultunifiedorder!=null) {
			//prepay_id从接口中获取
			req.prepayId = resultunifiedorder.get("prepay_id");
			req.packageValue = "prepay_id="+resultunifiedorder.get("prepay_id");
		}
		else {
			Toast.makeText(SonActivity.this, "prepayid为空", Toast.LENGTH_SHORT).show();
		}
		req.nonceStr = getNonceStr();
		req.timeStamp = String.valueOf(genTimeStamp());
		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
		req.sign = genAppSign(signParams);
		sb.append("sign\n"+req.sign+"\n\n");
		Log.e("Simon", "----"+signParams.toString());
	}
	//生成随机号，防重发
	private String getNonceStr() {
		// TODO Auto-generated method stub
		Random random=new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	//时间戳
	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}
	//获得app签名
	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);
		this.sb.append("sign str\n"+sb.toString()+"\n\n");
		String appSign = MD5.getMessageDigest(sb.toString().getBytes());
		Log.e("Simon","----"+appSign);
		return appSign;
	}

	/*支付宝支付*/
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case SDK_PAY_FLAG: {
					PayResult payResult = new PayResult((String) msg.obj);
					// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
					String resultInfo = payResult.getResult();
					String resultStatus = payResult.getResultStatus();
					// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
					if (TextUtils.equals(resultStatus, "9000")) {
						Toast.makeText(SonActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
						//addFragment(Fragment_share.newInstance(titlecontente,true),true);
					} else {
						// 判断resultStatus 为非“9000”则代表可能支付失败
						// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
						if (TextUtils.equals(resultStatus, "8000")) {
							Toast.makeText(SonActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
						} else {
							// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
							Toast.makeText(SonActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
						}
					}
					break;
				}
				case SDK_CHECK_FLAG: {
					Toast.makeText(SonActivity.this, "检查结果为：" + msg.obj,
							Toast.LENGTH_SHORT).show();
					break;
				}
				default:
					break;
			}
		};
	};

	/**
	 * call alipay sdk pay. 调用SDK支付
	 *
	 *//*
	public void pay(String title, String content, String price,String out_trade_no) {
		// 订单
		String orderInfo = getOrderInfo("主题", "内容", price,out_trade_no);
		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(SonActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	*//**
	 * create the order info. 创建订单信息
	 *
	 *//*
	public String getOrderInfo(String subject, String body, String price,String out_trade_no) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + ConstantsAl.PARTNER + "\"";
		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + ConstantsAl.SELLER + "\"";
		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + out_trade_no + "\"";
		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";
		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";
		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";
		// 服务器异步通知页面路径
		*//*orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";*//*
		orderInfo += "&notify_url=" + "\""
				+ "http://115.159.34.210:7880/pillar/api/authapi/zfbnotify"
				+ "\"";
		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";
		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";
		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";
		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";
		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";
		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";
		return orderInfo;
	}
	*//**
	 * sign the order info. 对订单信息进行签名
	 *
	 * @param content
	 *            待签名订单信息
	 *//*
	public String sign(String content) {
		return SignUtils.sign(content, ConstantsAl.RSA_PRIVATE);
	}
	*//**
	 * get the sign type we use. 获取签名方式
	 *
	 *//*
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}*/

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(mMessageReceiver, new IntentFilter("io.zhixun"));
	}

	// 接收推送过来的广播通知
	private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					// Extract mConversationList included in the Intent
					int code = intent.getIntExtra("PushId", 0);
					String content = intent.getStringExtra("Content");
					String title = intent.getStringExtra("Title");
					DialogFromMiddle dialogFormMiddle = new DialogFromMiddle(SonActivity.this);
					dialogFormMiddle.setSureListener(new DialogFromMiddle.Sure() {
						@Override
						public void onSure() {
							// TODO Auto-generated method stub
						}
					});
					dialogFormMiddle.show(title, content, "", "", getResources().getString(R.string.dialog_yes2),getResources().getString(R.string.dialog_no2), true);

				}
			};

}
